/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.panel.Category;
import model.panel.User;
import model.panel.SubCategoryPanel;

import java.sql.*;
import handler.database;

/**
 *
 * @author SONY VAIO
 */
public class SubCategoryPanelServlet extends HttpServlet {
      SubCategoryPanel subCategoryData;
     //ArrayList<Category> subcategorys;
     //ArrayList<User> moderators;

    public void init() throws ServletException{
        super.init();
    }

    private void getDatabaseSubCategory(int id) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        Connection conn = null;
        database db = new database();
        conn = db.getConnection();

        String strQuery = "SELECT * from category WHERE parent_id="+id;
        Statement statement = conn.createStatement();
        ResultSet result = statement.executeQuery(strQuery);

        System.out.println(strQuery);

        while(result.next()){
            int child_id = Integer.parseInt(result.getString(1));
            String categoryName = result.getString(2);
            int ownerId = Integer.parseInt(result.getString(3));
            int parentId = Integer.parseInt(result.getString(4));
            if(ownerId!=0) {
                String strQuery1 = "SELECT * from user WHERE id="+ownerId;
                Statement statement1 = conn.createStatement();
                ResultSet result1 = statement1.executeQuery(strQuery1);

                while(result1.next()){
                    String ownerName = result1.getString(2);
                    Category subcategory = new Category(child_id, categoryName, ownerId, parentId, ownerName);
                    subCategoryData.subcategorys.add(subcategory);
                }
            } else {
                Category subcategory = new Category(child_id, categoryName, ownerId, parentId, "none");
                subCategoryData.subcategorys.add(subcategory);
            }
        }
        conn.close();
    }

    private void getDatabaseModerator() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException{
        Connection conn = null;
        database db = new database();
        conn = db.getConnection();

        String strQuery = "SELECT * from user WHERE role='moderator'";
        Statement statement = conn.createStatement();
        ResultSet result = statement.executeQuery(strQuery);

        System.out.println(strQuery);

        while(result.next()){
            int id = Integer.parseInt(result.getString(1));
            String userName = result.getString(2);
            String passWord = result.getString(3);
            String email = result.getString(4);
            String role = result.getString(5);
            int numberRoom = Integer.parseInt(result.getString(6));
            int ban = Integer.parseInt(result.getString(7));
            
            User user = new User(id, userName, passWord, email, role, numberRoom, ban);
            subCategoryData.moderators.add(user);
        }
        conn.close();
    }
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        if(request.getParameter("action").toString().equalsIgnoreCase("insert"))
        {
            subCategoryData = new SubCategoryPanel();
            try {
                Connection conn = null;
                database db = new database();
                conn = db.getConnection();

                // Check if the input of user is moderator
                boolean IsModerator = false;
                int owner_id = 0;

                String user_name = request.getParameter("owner");
                String strQuery1 = "SELECT * from user where username='"+ user_name +"'";
                System.out.println(strQuery1);
                Statement statement1 = conn.createStatement();
                ResultSet result1 = statement1.executeQuery(strQuery1);

                 while(result1.next()){
                    if(result1.getString(5).equalsIgnoreCase("moderator")){
                        IsModerator = true;
                        owner_id = Integer.parseInt(result1.getString(1));
                    }
                 }

                 System.out.println(IsModerator);
                if(request.getParameter("subcategory") != null && request.getParameter("subcategory").length() > 0 && IsModerator == true){
                    String subcategory_name = request.getParameter("subcategory").toString();
                    int parent_id = Integer.parseInt(request.getParameter("id").toString());
                    String strQuery = "INSERT INTO category (name,owner_id,parent_id ) "
                            + "VALUES ('"+ subcategory_name + "',"+ owner_id +","+parent_id+")";
                    System.out.println(strQuery);
                    Statement statement = conn.createStatement();
                    int Result = statement.executeUpdate(strQuery);
                    out.println("succes");
                 } else {
                     out.println("fail");
                 }
            } catch (SQLException ex) {
                out.println("fail");
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                out.println("fail");
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                out.println("fail");
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                out.println("fail");
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                out.close();
            }
        } else  if(request.getParameter("action").toString().equalsIgnoreCase("get")){
            subCategoryData = new SubCategoryPanel();
            try {
                int id = Integer.parseInt(request.getParameter("id").toString());
                getDatabaseSubCategory(id);
                getDatabaseModerator();
            } catch (SQLException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(CategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            }

            try{
                Gson gson = new Gson();
                String stringSubCategory = gson.toJson(subCategoryData);
                System.out.println(stringSubCategory);
                out.println(stringSubCategory);
            }finally {
                out.close();
            }
        }else  if(request.getParameter("action").toString().equalsIgnoreCase("setcategoryname")){
            int result = 0;
            try {
                Connection conn = null;
                database db = new database();
                conn = db.getConnection();

                String CatName = request.getParameter("name").toString();
                int Id = Integer.parseInt(request.getParameter("id").toString());

                String strQuery = "UPDATE category SET name='"+ CatName  +"' WHERE id="+Id;
                Statement statement = conn.createStatement();
                result = statement.executeUpdate(strQuery);
            } catch (SQLException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            }finally {
                out.println(result);
                out.close();
            }
        }else  if(request.getParameter("action").toString().equalsIgnoreCase("setownername")){
            subCategoryData = new SubCategoryPanel();
            int result = 0;
            try {
                String newOwner = null;
                Connection conn = null;
                database db = new database();
                conn = db.getConnection();
                
                String CatName = request.getParameter("name").toString();
                int Id = Integer.parseInt(request.getParameter("id").toString());

                String strQuery = "UPDATE category SET owner_id="+ Id  +" WHERE name='"+CatName+"'";
                Statement statement = conn.createStatement();
                result = statement.executeUpdate(strQuery);

                String strQuery1 = "SELECT * from user where id="+ Id ;
                Statement statement1 = conn.createStatement();
                ResultSet result1 = statement1.executeQuery(strQuery1);

                while(result1.next()){
                   newOwner = result1.getString(2);
                }

                String strQuery2 = "SELECT * from category where name='"+CatName+"'";
                Statement statement2 = conn.createStatement();
                ResultSet result2 = statement2.executeQuery(strQuery2);

                while(result2.next()){
                   int id = Integer.parseInt(result2.getString(1));
                   String cat_name = result2.getString(2);
                   int owner_id = Integer.parseInt(result2.getString(3));
                   int par_id = Integer.parseInt(result2.getString(4));
                   Category subcategory = new Category(id, cat_name, owner_id, par_id, newOwner);
                   subCategoryData.subcategorys.add(subcategory);
                }
            } catch (SQLException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            }try{
                Gson gson = new Gson();
                String stringSubCategory = gson.toJson(subCategoryData);
                System.out.println(stringSubCategory);
                out.println(stringSubCategory);
            }finally {
                out.close();
            }
        }else  if(request.getParameter("action").toString().equalsIgnoreCase("setownersubcat")){
            int result = 0;
            try {
                Connection conn = null;
                database db = new database();
                conn = db.getConnection();

                String SubCatName = request.getParameter("name").toString();
                int Id = Integer.parseInt(request.getParameter("id").toString());

                String strQuery = "UPDATE category SET owner_id="+ Id  +" WHERE name='"+SubCatName+"'";
                Statement statement = conn.createStatement();
                result = statement.executeUpdate(strQuery);
                
            } catch (SQLException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            }finally {
                out.close();
            }
        } else if (request.getParameter("action").toString().equalsIgnoreCase("delete")) {
            int result = 0;
            try {
                String subcategory_name = request.getParameter("name").toString();
                Connection conn = null;
                database db = new database();
                conn = db.getConnection();

                String strQuery = "DELETE FROM category WHERE name='"+ subcategory_name +"'" ;
                Statement statement = conn.createStatement();
                result = statement.executeUpdate(strQuery);

            } catch (SQLException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            finally {
                out.close();
            }
        }else  if(request.getParameter("action").toString().equalsIgnoreCase("setsubcategoryname")){
            int result = 0;
            try {
                Connection conn = null;
                database db = new database();
                conn = db.getConnection();

                String SubCatName = request.getParameter("name").toString();
                int SubCatId = Integer.parseInt(request.getParameter("id").toString());

                String strQuery = "UPDATE category SET name='"+ SubCatName  +"' WHERE id="+SubCatId;
                Statement statement = conn.createStatement();
                result = statement.executeUpdate(strQuery);
            } catch (SQLException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(SubCategoryPanelServlet.class.getName()).log(Level.SEVERE, null, ex);
            }finally {
                out.println(result);
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
